package org.batatasframework.support.attribute;

import java.util.List;
import java.util.Map.Entry;

import org.batatasframework.expression.CommandExpressionExtra;
import org.batatasframework.expression.ExpressionClause;
import org.batatasframework.support.attribute.TableMetadataAttributeImpl.InternalFieldMetadataAttribute;
import org.batatasframework.support.database.IdentifyTableGenerator;
import org.batatasframework.support.database.metadatas.DatabaseMetadataResource;
import org.batatasframework.support.database.metadatas.TableMetadata;
import org.batatasframework.support.definition.impl.AbstractTableDefinitionParser;
import org.batatasframework.support.loader.DatabasePropertiesParser;
import org.batatasframework.values.ValueGetter;
import org.springframework.util.Assert;

import cn.bonoon.kernel.util.StringHelper;

public class AttributeTableDefinitionParser extends AbstractTableDefinitionParser{

	private void parseAttributeItem(
			TableMetadataAttributeImpl atMetdata, 
			ExpressionClause se/*, 
			List<ExpressionClause> attrs*/) throws Exception{
		
		CommandExpressionExtra command = new CommandExpressionExtra(se, 
				new String[]{"-c", "-t", "-n", "-u", "-o", "-f", "-max", "-min"}, 
				"options", "tooltip", "name", "format");
		command.identitfies("disabled", "editable", "required", "readable", "queryable", "PIC");
		command.fragments(".");
		
		InternalFieldMetadataAttribute afMetadata = atMetdata.createField(se.getName().toString());
		
		String unit = command.getString("-u");
		afMetadata.setUnit(unit);
		afMetadata.setTooltip(command.getString("tooltip"));
		afMetadata.setNeedPicture(command.getBoolean("PIC", false));
		
		String codeName = StringHelper.get(
				se.getExtra().getString(),        //优先
				command.getString("-c"),          //第二
				afMetadata.getName());            //最后
		afMetadata.setCodeName(codeName);              
		
		String title = StringHelper.get(
				command.getString("name"), 
				command.getString("-n"), 
				command.getString("-t"), 
				codeName);

		String headTitle = afMetadata.getHeadTitle();
		if(null == headTitle){//如果在之前已经进行了指定，则不再需要自动生成title了
			headTitle = codeName;
			if(codeName != title){
				headTitle += " " + title;
			}
			if(StringHelper.isNotEmpty(unit)){
				headTitle += "(" + unit + ")";
			}
		}
		
		afMetadata.setTitle(title);
		afMetadata.setHeadTitle(headTitle);
		
		afMetadata.setOrdinal(command.getInteger("-o",0));
		
		//注意" | "前后都是有空格的，如果没有空格，则会被认为是选项的一部分
		parseOptional(afMetadata, command);
		
		//存储起来
		atMetdata.put(afMetadata.getName(), afMetadata);
	}
	
	@Override
	protected TableMetadata buildTableMetadata(DatabasePropertiesParser parserContext) throws Exception {
		
//		parserContext.getSearchablePlatformRegsitry().registerSearchableHandlerBuilder(AttributeSearchableHandlerBuilder.handlerBuilder);
		
//		DatabaseMetadataResource databaseMetadataSources = parserContext.getDatabaseMetadataSources();
		
		
		TableMetadata tableMetadata = parserContext.getTableMetadata();
		String strName =  parserContext.getString("name", tableMetadata.getTableName());
		
		List<ExpressionClause> attrs = parserContext.getGroup("attribute").mergeOf();
		Assert.notEmpty(attrs, "属性表必须定义属性！");
		
		ExpressionClause attributeTables = parserContext.getExpression("attribute.tables");
		String[] ats = attributeTables.getString().split(",");
		
		TableMetadataAttributeImpl atMetdata = new TableMetadataAttributeImpl(
//				databaseMetadataSources, 
				tableMetadata, 
				strName,
				ats);
		
		for(Entry<String, ValueGetter> evs : attributeTables.extrasSet()){
			atMetdata.filter(evs.getKey(), evs.getValue().getString().split(","));
		}
		
		//TODO 删除数组里的对象
		for(ExpressionClause se : attrs){
		
		//while(!attrs.isEmpty()){
//			ExpressionClause se = attrs.remove(0);
			if(se.associated()) continue;
			
			parseAttributeItem(atMetdata, se/*, attrs*/);
		}

		/*
		 * 属性表定义的一些信息
		 */
		atMetdata.setVersion(parserContext.getInteger("version",0));
		atMetdata.setTitle(parserContext.getString("title"));
		atMetdata.setSeparateField(parserContext.getString("separate.field"));
		atMetdata.setMainField(parserContext.getString("main.field"));
		
		/* 需要在定义的时候就指定了有多少个表 */
//		atMetdata.setTableMapped(new MappedExpression(parserContext.getExpression("table.mapped")));
		atMetdata.setDefaultTableGenerator(parserContext.getObject("table.generator", IdentifyTableGenerator.class));
		//JsonExpression je = new JsonExpression(parserContext.getExpression("table.generator"));
		
		DatabaseMetadataResource.getResource().registTableMetadata(strName, atMetdata);
		return atMetdata;
	}

}
